package compiler;

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class OutputFormatter {

    private PrintWriter pw;
    private int nSpaces = 4;
    private int indentLevel = 0;
    private boolean doIndent = false;

    /**
     * Create a new OutputFormatter object that outputs to a file.
     * @param ofname output file name
     * @throws FileNotFoundException
     */
    public OutputFormatter(String ofname) throws FileNotFoundException {
        pw = new PrintWriter(ofname);
    }

    /**
     * Returns the number of spaces used for indenting.
     * @return The number of spaces used for indenting
     */
    public int getnSpaces() {
        return nSpaces;
    }

    /**
     * Sets the number of spaces used for indenting.
     * @param nSpaces The number of spaces used for indenting
     */
    public void setnSpaces(int nSpaces) {
        this.nSpaces = nSpaces;
    }
   
    /**
     * Increase indent level by 1.
     */
    public void increaseIndent() {
        indentLevel++;
    }
   
    /**
     * Decrease indent level by 1.
     */
    public void decreaseIndent() {
        indentLevel--;
    }

    /**
     * Outputs a given string.
     * @param str The string to output
     */
    public void output(String str) {
        if (doIndent) {
            // ToDo: get rid of this loop
            int x = indentLevel * nSpaces;
            while (x > 0) {
                space();
                x--;
            }
            doIndent = false;
        }
        pw.print(str);
    }

    /**
     * Ends a line.
     */
    public void endLine() {
        pw.println();
        doIndent = true;
    }
   
    /**
     * Outputs a string and ends the line.
     * @param string The string to output
     */
    public void outputln(String string) {
        output(string);
        endLine();
    }
   
    /**
     * Outputs a blank line.
     */
    public void outputBlankLine() {
        endLine();
    }

    /**
     * Outputs a space character.
     */
    public void space() {
        pw.print(' ');
    }
   
    /**
     * Closes the output, writing to the file.
     */
    public void close() {
        pw.close();
    }
}